package com.lxr0860.lxr0860production_test;

import static com.lxr0860.lxr0860production_test.utils.DeviceInfo.getIMEI;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;

import com.lxr0860.lxr0860production_test.utils.Utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class CheckInfoActivity extends Activity {

    TextView tv_info_sn;
    TextView tv_info;
    //    WifiReceiver wifiReceiver;
    WifiManager wifiManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_check);
        initView();
        initData();
    }

    protected void initView() {
        tv_info = findViewById(R.id.tv_check_info);
        tv_info_sn = findViewById(R.id.tv_check_info_sn);
    }

    @SuppressLint("MissingPermission")
    protected void initData() {
        BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();

        tv_info_sn.setText("\n流水号：" + getSn());
//        tv_info.setText("蓝牙MAC地址：" + defaultAdapter.getAddress());
        tv_info.setText("蓝牙MAC地址：" + getBtMac());
        tv_info.append("\nIMEI：" );

//        Log.e("BluMac", defaultAdapter.getAddress());
//        Log.e("IMEI", getIMEI(this));
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
<<<<<<< HEAD:app/src/main/java/com/lxr0860/lxr0860production_test/CheckInfoActivity.java
//        String wifiMac=getMacAddr();
//        if (wifiMac==null||wifiMac.length()<=0||
//                wifiMac.equals("fail")||wifiMac.equals("02:00:00:00:00:00")){
//            IntentFilter filter = new IntentFilter();
//            filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//            wifiReceiver=new WifiReceiver();
//            registerReceiver(wifiReceiver, filter);
//            wifiManager.setWifiEnabled(true);
//        }else {
//        }

        tv_info.append("\nWifi_MAC地址：" + getWlanMacAddress());
=======
        tv_info.append("\nWifi_MAC地址：" + devicEcon.get_sys_parameter(5));
>>>>>>> e4f272b5472579b3974abdf8f4069581f4fe75a7:app/src/main/java/com/lxr5002/lxr5002production_test/CheckInfoActivity.java
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (wifiReceiver!=null) {
//            unregisterReceiver(wifiReceiver);
//        }
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
    }


    //这样获取的mac地址不会在首次开机时在enable的广播中获取mac时依然返回0200000000
    public static String getMacAddr() {
        try {
            return loadFileAsString("/sys/class/net/wlan0/address")
                    .toUpperCase().substring(0, 17);
        } catch (IOException e) {
            e.printStackTrace();
            return "fail";
        }
    }

    private static String loadFileAsString(String filePath)
            throws IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }


    private String getSn() {
        return "";
    }

    public String getBtMac() {
        try{
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            Field field = bluetoothAdapter.getClass().getDeclaredField("mService");
            // 参数值为true，禁用访问控制检查
            field.setAccessible(true);
            Object bluetoothManagerService = field.get(bluetoothAdapter);
            if (bluetoothManagerService == null) {
                return null;
            }
            Method method = bluetoothManagerService.getClass().getMethod("getAddress");
            Object address = method.invoke(bluetoothManagerService);
            if (address != null && address instanceof String) {
                return (String) address;
            } else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /**
     * WIFI相关监听
     */
/*    private class WifiReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int extra = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (extra) {
                    case WifiManager.WIFI_STATE_ENABLED:
                        Log.e(":cly", "wifi已打开");
                        tv_info.append("\nWifi_MAC地址："+getMacAddr());
                        break;
                }
            }
        }
    }*/
    public String getWlanMacAddress() {

        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (networkInterface.getName().equals("wlan0")) {
                    StringBuilder mac = new StringBuilder();
                    byte[] hardwareAddress = networkInterface.getHardwareAddress();
//                    String hex = Integer.toHexString(hardwareAddress[0] & 0xff);
                    if (hardwareAddress == null) {
return "";
                    }
                    String hex = Utils.bytesToString(hardwareAddress);
                    if (hex.length() == 1) {
                        mac.append('0');
                    }
                    mac.append(hex);
                    for (int i = 1; i < hardwareAddress.length; ++i) {
                        mac.append(':');
                        hex = Integer.toHexString(hardwareAddress[i] & 0xff);
                        if (hex.length() == 1) {
                            mac.append('0');
                        }
                        mac.append(hex);
                    }
                    return mac.toString();
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return "";
    }
}
